package com.clkj.zhonghui.service.product;

import com.clkj.zhonghui.dao.product.CategoryMapper;
import com.clkj.zhonghui.pojo.common.OSSUtil;
import com.clkj.zhonghui.pojo.product.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：周佳润
 * @Date：2024/7/11 上午9:21
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    private List<Integer> idList;
    @Override
    public void addCategory(Category category, String flag, HttpServletRequest request) {
        MultipartFile file = ((MultipartRequest) request).getFile("file");
        String fileName = "";
        if (file != null) {
            fileName = OSSUtil.uploadingImg(file,"zhonghui/category");
        }
        if(fileName!=""){
            category.setCategoryPic(fileName);
        }
        if("add".equals(flag)){
            categoryMapper.insertSelective(category);
        }else{
            categoryMapper.updateByPrimaryKeySelective(category);
        }

    }

    @Override
    public List<Category> listCategory(String shopId) {
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        if (shopId != null && !shopId.equals(-1)) {
            criteria.andEqualTo("shopId", shopId);
        }
        List<Category> categoryList = categoryMapper.selectByExample(example);
        return categoryList;
    }

    @Override
    public void updateCategory(String cateIds,Integer categoryStatus) {
        List<Integer> idList = new ArrayList<>();
        String [] id = cateIds.split(",");
        for (String s : id) {
            idList.add(Integer.parseInt(s));
        }
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("categoryId",idList);
        Category category = new Category();
        category.setCategoryStatus(categoryStatus);

        categoryMapper.updateByExampleSelective(category,example);

    }

    @Override
    public void delCategory(String cateIds) {
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        String id [] = cateIds.split(",");
        idList = new ArrayList<>();
        for (String s : id) {
            idList.add(Integer.parseInt(s));
        }
        criteria.andIn("categoryId",idList);
        categoryMapper.deleteByExample(example);
        idList = null;
    }
}
